/**
 * 
 */
package com.iwords.utils;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONArray;
import org.json.JSONException;

/**
 * @author       BOLIN.HBC 
 * @time         2011-3-27    
 * @description  JSOBObject对象封装        
 */
public class JSONObject extends org.json.JSONObject {

	protected final Log log = LogFactory.getLog(this.getClass());
	
	private JSONArray keys = new JSONArray();
	private JSONArray values = new JSONArray();

	public JSONObject() {

		super();
		try {
			super.put("isSuccess", true);
		} catch (JSONException e) {
			log.error(e.getMessage(), e);
		}
	}
	
	public JSONObject putColumn(String... keys) {
		if (this.keys.length() > 0) {

			throw new RuntimeException("your key is already set");
		}
		if (keys.length == 0) {

			throw new RuntimeException("your key must have");
		}
		JSONArray ks = new JSONArray();
		for (String key : keys) {
			ks.put(key);
		}
		this.keys = ks;
		try {
			this.put("nk", ks);
		} catch (JSONException e) {
			log.error("json error", e);
		}
		return this;
	}

	public JSONObject putValue(Object... values) {
		if (this.keys.length() == 0) {

			throw new RuntimeException("your key is't  set");
		}
		if (values.length == 0 || values.length != this.keys.length()) {

			throw new RuntimeException("your key must be right");
		}
		JSONArray vas = new JSONArray();

		for (Object o : values) {
			vas.put(o);
		}
		this.values.put(vas);
		try {
			this.put("nv", this.values);
		} catch (JSONException e) {
			log.error("json error", e);
		}
		return this;
	}

	public JSONArray getArrays(org.json.JSONObject value) throws JSONException {
		JSONArray result = new JSONArray();
		JSONArray values = (JSONArray) value.get("nv");
		JSONArray keys = (JSONArray) value.get("nk");

		if (values == null || keys == null) {
			return null;
		}

		for (int j = 0; j < values.length(); j++) {
			JSONArray array = (JSONArray) values.get(j);
			org.json.JSONObject o = new org.json.JSONObject();
			for (int i = 0; i < keys.length(); i++) {
				o.put((String) keys.get(i), array.get(i));

			}
			result.put(o);

		}
		return result;
	}

}
